package de.gameduell.framework.asset {
//	import flash.events.EventDispatcher;
	
	import de.gameduell.framework.asset.IAsset;	

	/**
	 * @author GD
	 */
	public class AssetGroup extends Asset {

		private var loadedAssets:Array;
		private var assetsToLoad:Array;
//		private var _loaders:Array;
		private var assetMap:Array;

		public function AssetGroup(aId:String, aUrl:String) {
			super(aId, aUrl);
			loadedAssets = new Array();	
			assetsToLoad = new Array();
			assetMap     = new Array();
//			_loaders     = new Array();
		}
		
		override public function load():void {
			if(assetsToLoad.length == 0){
				dispatchEvent(new AssetEvent(AssetEvent.COMPLETE,this));
			} else {
				var asset:IAsset = assetsToLoad[0];
				asset.addEventListener(AssetEvent.COMPLETE, assetLoaded);
				asset.addEventListener(AssetEvent.PROGRESS, progress);
				asset.addEventListener(AssetEvent.LOAD_ERROR, onError);
				asset.load();
			}
		}
		
		private function onError(event:AssetEvent):void {
			dispatchEvent(event);
		}

		override public function get data():Object{
			return loadedAssets;		
		}
		
		override public function get percentLoaded():int{
			var totalAssets:int  = assetsToLoad.length + loadedAssets.length;;
			var segPercent:int   = Math.round(( loadedAssets.length/totalAssets)*100);	
			var asset:IAsset     = assetsToLoad[0];
			var totalPercent:int = Math.round(asset.percentLoaded/totalAssets) + segPercent;
			
			return  totalPercent;;
		}

		public function addAsset(aAsset:IAsset):void {
			assetsToLoad.push(aAsset);
//			if (aAsset.loader != null){
//				_loaders.push(aAsset.loader);
//			}
			assetMap[aAsset.id] = aAsset;
		}
		
		public function getAssetById(id:String):IAsset{
			return assetMap[id];
		}
		
		public function assetExists(id:String):Boolean{
			return assetMap[id] != undefined;
		}
		
		/**
		 * moves an asset to position 1 in the array. that way, it is next to be loaded
		 * @param anAsset:IAsset asset to be moved up the list
		 */
		public function moveAssetUp(anAsset:IAsset):void {
			var assetIndex:int = assetsToLoad.indexOf(anAsset);
			if (assetIndex > 0){
				assetsToLoad.splice(1, 0,assetsToLoad.splice(assetIndex, 1));
			}
		}
		
		private function assetLoaded(event:AssetEvent):void {
			var loadedAsset:IAsset = assetsToLoad.shift();
			loadedAssets.push(loadedAsset);
			if(assetsToLoad.length == 0){
				dispatchEvent(new AssetEvent(AssetEvent.COMPLETE,this));
			}else{
				load();
			}
		}
		
		public function get assets():Array{
			return loadedAssets;
		}
		
//		public function get loaders():Array{
//			return _loaders;
//		}
	}
}
